import React, { useState, useEffect } from 'react';
import { updateDomain, checkDomainName } from '../api/client';
import './EditVMDialog.css';

interface Domain {
  uuid: string;
  name: string;
  memory: number; // bytes
  cpus: number;
  autostart: boolean;
  state: string;
}

interface EditVMDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: (vm: any) => void;
  domain: Domain | null;
}

interface VMEditFormData {
  name: string;
  memory: number;
  vcpus: number;
  autostart: boolean;
}

const EditVMDialog: React.FC<EditVMDialogProps> = ({ isOpen, onClose, onSuccess, domain }) => {
  const [formData, setFormData] = useState<VMEditFormData>({
    name: '',
    memory: 1024,
    vcpus: 1,
    autostart: false
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [originalData, setOriginalData] = useState<VMEditFormData | null>(null);

  useEffect(() => {
    if (domain) {
      const initialData = {
        name: domain.name,
        memory: Math.round(domain.memory / 1024 / 1024), // 转换为MB (从bytes)
        vcpus: domain.cpus,
        autostart: domain.autostart
      };
      setFormData(initialData);
      setOriginalData(initialData);
    }
  }, [domain]);

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = '虚拟机名称不能为空';
    } else if (formData.name.length < 1 || formData.name.length > 64) {
      newErrors.name = '虚拟机名称长度必须在1-64个字符之间';
    } else if (!/^[a-zA-Z0-9_-]+$/.test(formData.name)) {
      newErrors.name = '虚拟机名称只能包含字母、数字、下划线和连字符';
    }

    if (formData.memory < 128) {
      newErrors.memory = '内存不能小于128MB';
    } else if (formData.memory > 1048576) { // 1TB
      newErrors.memory = '内存不能超过1TB';
    }

    if (formData.vcpus < 1) {
      newErrors.vcpus = 'CPU核心数不能小于1';
    } else if (formData.vcpus > 256) {
      newErrors.vcpus = 'CPU核心数不能超过256';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleInputChange = (field: keyof VMEditFormData, value: string | number | boolean) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // 清除对应字段的错误
    if (errors[field]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  const checkNameAvailability = async (name: string) => {
    if (name === originalData?.name) {
      return true; // 名称未改变，无需检查
    }

    try {
      const response = await checkDomainName(name);
      return !response.data.exists;
    } catch (error) {
      console.error('检查名称失败:', error);
      return false;
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm() || !domain) {
      return;
    }

    // 检查名称是否可用
    if (formData.name !== originalData?.name) {
      const isNameAvailable = await checkNameAvailability(formData.name);
      if (!isNameAvailable) {
        setErrors(prev => ({ ...prev, name: '该虚拟机名称已存在' }));
        return;
      }
    }

    setIsSubmitting(true);

    try {
      // 只发送有变化的字段
      const updateData: any = {};

      if (formData.name !== originalData?.name) {
        updateData.name = formData.name;
      }
      if (formData.memory !== originalData?.memory) {
        updateData.memory = formData.memory;
      }
      if (formData.vcpus !== originalData?.vcpus) {
        updateData.vcpus = formData.vcpus;
      }
      if (formData.autostart !== originalData?.autostart) {
        updateData.autostart = formData.autostart;
      }

      // 如果没有变化，直接关闭
      if (Object.keys(updateData).length === 0) {
        onClose();
        return;
      }

      const response = await updateDomain(domain.uuid, updateData);
      onSuccess(response.data);
      onClose();
    } catch (error: any) {
      console.error('更新虚拟机失败:', error);
      const errorMessage = error.response?.data?.detail || error.response?.data?.error || '更新虚拟机失败';
      setErrors({ submit: errorMessage });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleClose = () => {
    if (isSubmitting) return;
    setErrors({});
    onClose();
  };

  const hasChanges = () => {
    if (!originalData) return false;
    return (
      formData.name !== originalData.name ||
      formData.memory !== originalData.memory ||
      formData.vcpus !== originalData.vcpus ||
      formData.autostart !== originalData.autostart
    );
  };

  if (!isOpen || !domain) return null;

  return (
    <div className="modal-overlay" onClick={handleClose}>
      <div className="modal-content edit-vm-modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <div className="modal-header-left">
            <div className="vm-icon">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                <path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 18H4V4h16v16zM6 6h12v2H6zm0 4h12v2H6zm0 4h8v2H6z"/>
              </svg>
            </div>
            <div className="modal-title-info">
              <h2>编辑虚拟机</h2>
              <p className="vm-name-display">{domain.name}</p>
            </div>
          </div>
          <button className="modal-close" onClick={handleClose} disabled={isSubmitting}>
            ✕
          </button>
        </div>

        <form onSubmit={handleSubmit} className="vm-edit-form">
          <div className="form-content">
            <div className="form-section">
              <h3>基本信息</h3>

              <div className="form-group">
                <label htmlFor="vm-name" className="form-label">
                  虚拟机名称
                  <span className="required">*</span>
                </label>
                <div className="input-wrapper">
                  <input
                    id="vm-name"
                    type="text"
                    value={formData.name}
                    onChange={(e) => handleInputChange('name', e.target.value)}
                    className={errors.name ? 'error' : ''}
                    disabled={isSubmitting}
                    placeholder="输入虚拟机名称"
                  />
                  {errors.name && <span className="error-message">{errors.name}</span>}
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label htmlFor="vm-memory" className="form-label">
                    内存
                    <span className="required">*</span>
                    <span className="unit">(MB)</span>
                  </label>
                  <div className="input-wrapper">
                    <input
                      id="vm-memory"
                      type="number"
                      value={formData.memory}
                      onChange={(e) => handleInputChange('memory', parseInt(e.target.value) || 0)}
                      className={errors.memory ? 'error' : ''}
                      disabled={isSubmitting}
                      min="128"
                      max="1048576"
                    />
                    {errors.memory && <span className="error-message">{errors.memory}</span>}
                  </div>
                </div>

                <div className="form-group">
                  <label htmlFor="vm-vcpus" className="form-label">
                    CPU核心数
                    <span className="required">*</span>
                  </label>
                  <div className="input-wrapper">
                    <input
                      id="vm-vcpus"
                      type="number"
                      value={formData.vcpus}
                      onChange={(e) => handleInputChange('vcpus', parseInt(e.target.value) || 1)}
                      className={errors.vcpus ? 'error' : ''}
                      disabled={isSubmitting}
                      min="1"
                      max="256"
                    />
                    {errors.vcpus && <span className="error-message">{errors.vcpus}</span>}
                  </div>
                </div>
              </div>

              <div className="form-group">
                <label className="checkbox-label">
                  <input
                    type="checkbox"
                    checked={formData.autostart}
                    onChange={(e) => handleInputChange('autostart', e.target.checked)}
                    disabled={isSubmitting}
                  />
                  <span className="checkbox-text">开机自启动</span>
                </label>
              </div>

              {domain.state === 'running' && (
                <div className="info-banner">
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor" className="info-icon">
                    <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
                    <path d="M7.002 11a1 1 0 1 1 2 0 1 1 0 0 1-2 0zM7.1 4.995a.905.905 0 1 1 1.8 0l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 4.995z"/>
                  </svg>
                  <span>虚拟机正在运行，部分配置可能需要重启才能生效</span>
                </div>
              )}
            </div>
          </div>

          {errors.submit && (
            <div className="error-message global-error">
              {errors.submit}
            </div>
          )}

          <div className="modal-footer">
            <button
              type="button"
              className="btn-secondary"
              onClick={handleClose}
              disabled={isSubmitting}
            >
              取消
            </button>
            <button
              type="submit"
              className="btn-primary"
              disabled={isSubmitting || !hasChanges()}
            >
              {isSubmitting ? (
                <>
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor" className="loading-spinner">
                    <path d="M8 3a5 5 0 1 0 4.546 2.914.5.5 0 0 1 .908-.417A6 6 0 1 1 8 2v1z"/>
                    <path d="M8 4.466V.534a.25.25 0 0 1 .41-.192l2.36 1.966c.12.1.12.284 0 .384L8.41 4.658A.25.25 0 0 1 8 4.466z"/>
                  </svg>
                  保存中...
                </>
              ) : '保存'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default EditVMDialog;